﻿using System;
using System.Collections.Generic;
using System.Data;
using System.DirectoryServices;
using System.Linq;
using System.Web;

namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// adHandler 的摘要说明
    /// </summary>
    public class adHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string action = context.Request.Form["action"];
            string username = context.Request.Form["username"];
            string oupath = context.Request.Form["oupath"];
            string op = context.Request.Form["op"];
            string oppwd = context.Request.Form["oppwd"];


            cunReturn returnModel = new cunReturn();
            returnModel.Success = false;

            if (action == "GetList")
            {
                string sql = "SELECT controller,domain,op,oppwd,OU1,OU2,OU3 FROM ad";
                List<ServerModel> list = new List<ServerModel>();
                DataTable dt = SqlHelper.ExecuteDataTable(sql);
                if (dt.Rows.Count < 1)
                {
                    returnModel.Message = "未获取到记录，请联系管理员";
                }
                else
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ServerModel model = new ServerModel()
                        {
                            controller = dt.Rows[i][0].ToString(),
                            domain = dt.Rows[i][1].ToString(),
                            op = dt.Rows[i][2].ToString(),
                            oppwd = dt.Rows[i][3].ToString(),
                            OU1 = dt.Rows[i][4].ToString(),
                            OU2 = dt.Rows[i][5].ToString(),
                            OU3 = dt.Rows[i][6].ToString()
                        };
                        list.Add(model);
                    }
                    returnModel.Success = true;

                    returnModel.Data = JsonSerialize.Serialize(list);
                }
                context.Response.Write(JsonSerialize.Serialize(returnModel));
            }
            else if (action == "Create")
            {
                //有效性检查
                if (string.IsNullOrEmpty(op)||string.IsNullOrEmpty(oppwd)||string.IsNullOrEmpty(username)||string.IsNullOrEmpty(oupath))
                {
                    context.Response.Write("参数错误，请联系管理员");
                    return;
                }

                try
                {
                    using (DirectoryEntry entry = new DirectoryEntry(oupath, op, oppwd))
                    {
                        DirectorySearcher searcher = new DirectorySearcher(entry);
                        // 获取目标OU的DirectoryEntry对象
                        DirectoryEntry targetOU = new DirectoryEntry(oupath, op, oppwd);
                        // 创建新的域用户
                        DirectoryEntry newUser = targetOU.Children.Add("CN=" + username, "user");
                        newUser.Properties["samAccountName"].Value = username;
                        //newUser.Properties["userPrincipalName"].Value = username + "@" + tbDomainName.Text.ToLower();
                        newUser.CommitChanges();
                        newUser.Invoke("SetPassword", new object[] { "cbc123456+" });
                        newUser.Properties["userAccountControl"].Value = 0x200; // 启用用户账户
                        newUser.CommitChanges();
                    }
                    context.Response.Write(string.Format("域用户【{0}】创建成功！", username));
                }
                catch (Exception err)
                {
                    context.Response.Write(err.Message);
                }
            }
            else if (action == "Reset") 
            {
                //有效性检查
                if (string.IsNullOrEmpty(op) || string.IsNullOrEmpty(oppwd) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(oupath))
                {
                    context.Response.Write("参数错误，请联系管理员");
                    return;
                }
                try
                {
                    using (DirectoryEntry entry = new DirectoryEntry(oupath, op, oppwd))
                    {
                        DirectorySearcher searcher = new DirectorySearcher(entry);
                        searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", username); // 根据 sAMAccountName 属性查询用户对象
                        SearchResult result = searcher.FindOne();

                        if (result != null && !String.IsNullOrEmpty(result.Path))
                        {
                            DirectoryEntry userEntry = result.GetDirectoryEntry();
                            userEntry.InvokeSet("IsAccountLocked", false);
                            userEntry.Invoke("SetPassword", new object[] { "cbc123456+" });
                            userEntry.CommitChanges();
                            userEntry.Close();
                            context.Response.Write(string.Format("已成功重置用户 {0}", username));
                        }
                        else
                        {
                            context.Response.Write(string.Format("未找到用户 {0}", username));
                        }
                    }
                }
                catch (Exception err)
                {
                    context.Response.Write(err.Message);
                }
            }
            else if (action=="Delete")
            {
                //有效性检查
                if (string.IsNullOrEmpty(op) || string.IsNullOrEmpty(oppwd) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(oupath))
                {
                    context.Response.Write("参数错误，请联系管理员");
                    return;
                }
                try
                {
                    using (DirectoryEntry entry = new DirectoryEntry(oupath, op, oppwd))
                    {
                        DirectorySearcher searcher = new DirectorySearcher(entry);
                        searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", username); // 根据 sAMAccountName 属性查询用户对象
                        SearchResult result = searcher.FindOne();

                        if (result != null && !String.IsNullOrEmpty(result.Path))
                        {
                            DirectoryEntry userEntry = result.GetDirectoryEntry();

                            userEntry.DeleteTree(); // 递归删除该用户及其相关对象

                            context.Response.Write(string.Format("已成功删除用户 {0}", username));
                        }
                        else
                        {
                            context.Response.Write(string.Format("未找到用户 {0}", username));
                        }
                    }
                }
                catch (Exception err)
                {
                    context.Response.Write(err.Message);
                }
            }
            else if (action == "GetUsers")
            {
                //有效性检查
                if (string.IsNullOrEmpty(op) || string.IsNullOrEmpty(oppwd) || string.IsNullOrEmpty(oupath))
                {
                    context.Response.Write("参数错误，请联系管理员");
                    return;
                }

                List<ADUserModel> list = new List<ADUserModel>();
                using (DirectoryEntry entry = new DirectoryEntry(oupath, op, oppwd))
                {
                    using (DirectorySearcher searcher = new DirectorySearcher(entry))
                    {
                        // 设置过滤器以检索所有对象（用户、组、组织单位等）。
                        searcher.Filter = "(&(objectCategory=person)(objectClass=user))";

                        // 设置要检索的属性。如有需要，你可以添加更多属性。
                        searcher.PropertiesToLoad.Add("name");
                        searcher.PropertiesToLoad.Add("samAccountName");

                        try
                        {
                            SearchResultCollection result = searcher.FindAll();
                            foreach (SearchResult sr in result)
                            {
                                ADUserModel model = new ADUserModel() {
                                    name = sr.Properties["name"][0].ToString(),
                                    account=sr.Properties["samAccountName"][0].ToString()
                                };
                                list.Add(model);
                            }
                            returnModel.Success = true;
                            returnModel.Data = JsonSerialize.Serialize(list);
                        }
                        catch (Exception ex)
                        {
                            returnModel.Message = ex.Message;
                        }
                    }
                }
                context.Response.Write(JsonSerialize.Serialize(returnModel));
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}